package tk.leafotto.sign2.utils;

import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class FileUtil {

    public int save2SD(String data){
        int result = 0;
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            String sdPath = Environment.getExternalStorageDirectory().getPath();
            File file = new File(sdPath, "sign_bak_data_" + TimeUtil.getDateTimeNumber());
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(data.getBytes());
                fos.close();
                result = 1;
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                return result;
            }
        }else {
            return -1;
        }
    }

    public ArrayList<String> getRestoreFileList(){
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            String sdPath = Environment.getExternalStorageDirectory().getPath();
            File file = new File(sdPath);
            String[] files = file.list();
            ArrayList<String> fileList = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                if (files[i].startsWith("sign_bak_data")) {
                    fileList.add(files[i]);
                }
            }
            return fileList;
        }
        return null;
    }

    public String[] restoreFromSD(String fileName){
        String[] result = new String[2];
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            String sdPath = Environment.getExternalStorageDirectory().getPath();
            File file = new File(sdPath, fileName);
            if(file.exists()){
                try {
                    FileInputStream fis = new FileInputStream(file);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    String line;
                    int i = 0;
                    while ((line = br.readLine()) != null){
                        result[i] = line;
                        i++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
